'use client';

import React from 'react';
import { Card, CardBody, CardHeader, CardFooter, Divider, Chip } from "@nextui-org/react";
import { formatDate } from '@/app/utils/dateUtils';
import './NoteContent.css'; // 确保创建此CSS文件

interface NoteProps {
  note: {
    id?: number;
    title?: string;
    content?: string;
    tags?: string[];
    createdAt?: string;
    updatedAt?: string;
    isPublic?: boolean;
  };
}

// 安全处理Markdown内容的函数，将Markdown转换为安全HTML字符串
const renderMarkdown = (content: string): string => {
  if (!content) return '';
  
  // 处理标题
  content = content.replace(/^(#{1,6})\s+(.*?)$/gm, (_, hashes, text) => {
    const level = hashes.length;
    return `<h${level}>${text}</h${level}>`;
  });
  
  // 处理段落
  content = content.replace(/^(?!\s*#{1,6}\s+)(.*?)$/gm, '<p>$1</p>');
  
  // 处理粗体
  content = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
  
  // 处理斜体
  content = content.replace(/\*(.*?)\*/g, '<em>$1</em>');
  
  // 简单处理代码块
  content = content.replace(/```(.*?)```/gs, '<pre><code>$1</code></pre>');
  
  // 处理水平线
  content = content.replace(/^---$/gm, '<hr/>');
  
  // 处理链接
  content = content.replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>');
  
  return content;
};

export default function NoteContent({ note }: NoteProps) {
  // 渲染笔记内容
  const renderContent = (content?: string) => {
    if (!content) return <p>No content</p>;
    
    // 安全地将Markdown渲染为HTML元素数组
    const htmlContent = renderMarkdown(content);
    
    // 将HTML字符串包裹在div中显示
    return (
      <div className="prose prose-sm md:prose-base lg:prose-lg max-w-none">
        {htmlContent.split('\n').map((line, index) => (
          <div key={index}>{line}</div>
        ))}
      </div>
    );
  };

  return (
    <Card className="w-full h-full">
      <CardHeader className="flex flex-col items-start gap-2 px-6 pt-6">
        <h1 className="text-2xl font-bold">{note.title || 'Untitled Note'}</h1>
        <div className="flex items-center gap-2 text-sm text-default-500">
          <span>Created: {formatDate(note.createdAt)}</span>
          {note.updatedAt && <span>• Updated: {formatDate(note.updatedAt)}</span>}
          {note.isPublic && <Chip size="sm" color="success">Public</Chip>}
        </div>
      </CardHeader>
      <Divider/>
      <CardBody className="px-6 py-4 overflow-auto">
        {renderContent(note.content)}
      </CardBody>
      {note.tags && note.tags.length > 0 && (
        <>
          <Divider/>
          <CardFooter className="px-6 py-4">
            <div className="flex flex-wrap gap-2">
              {note.tags.map((tag, index) => (
                <Chip key={index} variant="flat">{tag}</Chip>
              ))}
            </div>
          </CardFooter>
        </>
      )}
    </Card>
  );
} 